const TaskModel = require("../orm/model/Task");
const text2Image = require("./action/text2Image");
const img2Img = require("./action/img2Img");
const FILE_STATUS = 3;
const SUCCESS_STATUS = 2;
const RUNING_STATUS = 1;
class Task {
  constructor() {}
  empty = true;
  id = null;
  data = null;
  async run() {
    await TaskModel.update(
      { status: RUNING_STATUS },
      { where: { id: this.id } }
    );
    let result = {};
    try {
      if (this.data.type == "img2img") {
        result = await img2Img(this.data);
      } else {
        result = await text2Image(this.data);
      }
      await this.success(result);
    } catch (error) {
      console.error("errr", error);
      await this.fail(error);
    }
  }
  async success(result) {
    await TaskModel.update(
      { status: SUCCESS_STATUS, result: JSON.stringify(result) },
      { where: { id: this.id } }
    );
  }
  async fail(error) {
    await TaskModel.update({ status: FILE_STATUS,failReason:JSON.stringify(error) }, { where: { id: this.id } });
  }

  async query() {
    try {
      const res = await TaskModel.findOne({
        // limit: 1,
        where: {
          status: 0,
        },
      });
      console.log("要处理任务了啊", res);
      if (res) {
        this.empty = false;
        const item = res.dataValues;
        this.id = item.id;
        this.data = item;
      } else {
        console.log("没任务啊");
      }
    } catch (error) {
      this.empty = true;
      console.error("运行错误", error);
    }
  }
}
module.exports = Task;
